//
//  YNMessage.m
//  Messenger
//
//  Created by iOS on 15/5/14.
//  Copyright (c) 2015年 YN-APP-iOS. All rights reserved.
//

#import "YNMessage.h"
#import "PictureModel.h"
#import "VoiceModel.h"
#import "YNUser.h"
#import "XMPPFramework.h"
#import "YNContactManager.h"
#import "YNMessageContactManager.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"
#import "YNManyPeopleChat.h"
#import "YNTwoPeopleChat.h"
#import "PictureModel.h"
@implementation YNMessage



#pragma initMethod

#pragma mark recivie xmppMessage for creat message model
/**
 *  接收消息的时候, 根据Message创建YNMessage对象
 */
- (instancetype)initWithXMPPMessage:(XMPPMessage *)messageXP messageSourceType:(GroupMessageSourceType)sourceType isFromSessionListLastMessage:(BOOL)isList

{
    self = [super init];
    if (self)
    {
        [self fromMessage:messageXP messageSourceType:sourceType isFromSessionListLastMessage:isList];
    }
    
    return self;
}

- (void)fromMessage:(XMPPMessage *)message messageSourceType:(GroupMessageSourceType)sourceType isFromSessionListLastMessage:(BOOL)isList
{
    NSString *sendTime = [[message elementForName:@"sendTime"] stringValue];
    NSString *covertStr = [YNMessage covertJsonWithHTML:message.body];
    if ([YNIMTool isEmptyString:covertStr]) {
        covertStr=@"";
    }
    self.message = covertStr;
    
    NSDictionary *messageBody = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:covertStr];
    int msgType = 0;
    
    if (messageBody)
    {
        //消息体
        self.body = [messageBody objectForKey:@"content"];
        self.text = [messageBody objectForKey:@"content"];
        if ([YNIMTool isEmptyString:self.body]) {
            self.body=@"";
        }
        if ([YNIMTool isEmptyString:self.text]) {
            self.text=@"";
        }
        /*
         根据Content判断消息里面包含哪些东西(图片? 文本? 表情?)
         ......*/
        
        
        //消息类型
        msgType = [[messageBody objectForKey:@"msgType"] intValue];
        if (msgType==YNBubbleMessageChatTypeLive) {
            self.messageMediaType = YNBubbleMessageLive;
        }
        if(msgType==YNBubbleMessageChatTypeWeChatVoice || msgType == YNBubbleMessageChatTypeGroupChatVoice || msgType == YNBubbleMessageChatTypeDiscussionVoice)
        {
            self.messageMediaType = YNBubbleMessageVoice;
            
            NSMutableDictionary * voice = [messageBody objectForKey:@"voice"];
            
            
            NSString * time =[[voice objectForKey:@"time"] copy];
            
            self.voiceDuration =time;
            
        }
        else
        {
            if (self.messageMediaType != YNBubbleMessageLive) {
                NSArray *files = [messageBody objectForKey:@"files"];
                if (files.count)
                {
                    self.messageMediaType = YNBubbleMessageFile;
                }
                
                NSArray *images = [messageBody objectForKey:@"images"];
                if (images.count)
                {
                    self.messageMediaType = YNBubbleMessagePhoto;
                }
                
                if(!images.count && !files.count)
                {
                    self.messageMediaType = YNBubbleMessageText;
                }
            }
        }
        //发送者的名字
        self.friendName = [messageBody objectForKey:@"sendName"];
    }else{
        self.subject = [[message elementForName:@"subject"] stringValue];
    }
    
    NSXMLElement *recipient = [message elementForName:@"recipient"];
    
    if ([[recipient xmlns] isEqualToString:@"com:yineng:broadcast"])
    {
        msgType = YNBubbleMessageChatTypeBroadcast;
        
        YNUser *user = [YNContactManager queryUserNameByUserID:[message from].user chatType:YNBubbleMessageChatTypeWeChat];
        
        self.friendName = user.userName;
        self.avatarUrl = user.headUrl;
    }
    
    //-------2018-1-24JC添加-增加撤回判断-----//
    NSXMLElement * unmark = [message elementForName:@"unmark"];
    if(unmark != nil)
    {
        self.isMessageWithdraw = YES;
    }
    //-------2018-1-24JC添加-增加撤回判断-----//
    self.sendTime = sendTime;
    self.currentTime = [self dateStringFromMINDate:sendTime];
    if (msgType==YNBubbleMessageChatTypeLive) {
        self.fromUserId = [message from].resource;
    }else{
        self.fromUserId = [message from].user;
    }
    self.toUserId = [message to].user;
    self.sendState = YNMessageSendStateSuccess;
    self.bubbleMessageType = YNBubbleMessageTypeReceiving;
    self.friendId = self.fromUserId;
    self.packetId = message.elementID;
    self.chatType = msgType;
    /**HX** 当消息type为YNBubbleMessageChatTypeAutoReplyOnPC类型时，现在是和YNBubbleMessageChatTypeWeChat类型的消息体解析方式、代码逻辑都是一样的所以在这里解析时直接将YNBubbleMessageChatTypeAutoReplyOnPC类型赋为YNBubbleMessageChatTypeWeChat **/
    if (self.chatType==YNBubbleMessageChatTypeAutoReplyOnPC) {
        self.chatType=YNBubbleMessageChatTypeWeChat;
    }
    
    //判断主体消息类型处理
    switch (self.chatType) {
            //        case YNBubbleMessageChatTypeWeChat:
        case YNBubbleMessageChatTypeWeChat:
        case YNBubbleMessageChatTypeWeChatVoice:
        case YNBubbleMessageChatTypeFileWeChat:
        {
            self.subject = [[message elementForName:@"subject"] stringValue];
            /**HX** 区分消息是自己发出的，做相应数据的调换 **/
            if ([self.fromUserId isEqualToString:[YNIMmanager sharedInstance].userImId]) {
                self.bubbleMessageType = YNBubbleMessageTypeSending;
                if (sourceType==GroupMessageSourceType_Roaming) {
                    self.fromUserId = [message to].user;
                    self.toUserId = [message from].user;
                    YNUser *user = [YNIMmanager queryUserWithUserNo:self.fromUserId];
                    self.friendName = user.userName;
                    self.friendId = self.fromUserId;
                }else{
                    YNUser *user = [YNIMmanager queryUserWithUserNo:self.toUserId];
                    self.friendName = user.userName;
                    self.friendId = self.toUserId;
                }
            }
        }
            break;
        case YNBubbleMessageChatTypeBroadcast:
        {
            self.subject = [[message elementForName:@"subject"] stringValue];
        }
            break;
        case YNBubbleMessageChatTypeDiscussion:
        case YNBubbleMessageChatTypeGroupChat:
        case YNBubbleMessageChatTypeProjectTeamChat:
        case YNBubbleMessageChatTypeDiscussionVoice:
        case YNBubbleMessageChatTypeGroupChatVoice:
        case YNBubbleMessageChatTypeProjectTeamVoice:
        case YNBubbleMessageChatTypeMeetingGroupChat:
        {
            self.fromUserId = [message from].resource;
            //普通接收的消息解析方式
            if ([[message from].resource isEqualToString:[YNIMmanager sharedInstance].userImId]) {
                self.bubbleMessageType = YNBubbleMessageTypeSending;
                self.fromUserId = [message to].user;
                self.toUserId = [message from].user;
            }
            /**HX** 如果是群会话类型，那选出项目组类型，然后重新对chatType赋值 **/
            if (self.chatType == YNBubbleMessageChatTypeGroupChat) {
                if ([self.friendId rangeOfString:ProjectTeamFlag].length > 0) {
                    self.chatType = YNBubbleMessageChatTypeProjectTeamChat;
                }
            }
            if (self.chatType == YNBubbleMessageChatTypeGroupChatVoice) {
                if ([self.friendId rangeOfString:ProjectTeamFlag].length > 0) {
                    self.chatType = YNBubbleMessageChatTypeProjectTeamVoice;
                }
            }
        }
            break;
        case YNBubbleMessageChatTypeNotification:
            break;
        default:
            break;
    }
    
    if (self.chatType == YNBubbleMessageChatTypeBroadcast)
    {
        NSString *messageType = [messageBody objectForKey:@"messageType"];
        if (messageType)
        {
            if ([messageType intValue] == 2)
            {
                NSString *content = [messageBody objectForKey:@"content"];
                self.text = [NSString stringWithFormat:@"%@",[YNMessage extractContentFromString:content]];
            }
            else
            {
                self.sourceTerminal = [[messageBody objectForKey:@"sourceTerminal"] integerValue];
                self.chatType = YNBubbleMessageChatTypeNotification;
            }
            
        }
    }
}

#pragma end

#pragma mark creat message model from dababase
/**
 *  根据多人会话数据表创建消息对象
 */
- (instancetype)initMessageWithManyPeopleChatTabel:(YNManyPeopleChat *)manyPeopleChat fileUploadUrlServer:(NSString*)fileUrlServer voicePath:(NSString*)voicePath
{
    self = [super init];
    if (self)
    {
        self.text = manyPeopleChat.message;
        self.body = manyPeopleChat.content;
        self.bubbleMessageType = manyPeopleChat.masterType;
        self.sendTime = manyPeopleChat.mTime;
        self.currentTime = self.sendTime;
        self.friendName = manyPeopleChat.sendName;
        self.sendState = manyPeopleChat.isSuccess;
        self.fromUserId = manyPeopleChat.fromUserNo;
        self.toUserId = manyPeopleChat.toUserNo;
        self.isRead = manyPeopleChat.isReaded;
        self.friendId = manyPeopleChat.groupNo;
        self.packetId = manyPeopleChat.packetId;
        self.friendName = manyPeopleChat.sendName;
        self.fileName = manyPeopleChat.fileName;
        self.isMessageWithdraw = manyPeopleChat.isMessageWithdraw;
        self.aitContactMarkArray =manyPeopleChat.aitContactMarkArray;
        self.messageHeight = manyPeopleChat.messageHeight;
        
        //2016-7-15jc添加
        NSString * messageBody =[manyPeopleChat.messageBody copy];
        
        NSDictionary *msgDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:messageBody];
        
        NSString * msgType =[[msgDic objectForKey:@"msgType"] copy];
        
        
        NSInteger msgTypeInterger = [msgType integerValue];
        
        if(msgTypeInterger == YNBubbleMessageChatTypeWeChatVoice ||msgTypeInterger == YNBubbleMessageChatTypeGroupChatVoice || msgTypeInterger == YNBubbleMessageChatTypeDiscussionVoice)
        {
            NSMutableDictionary * voiceDic =[[msgDic objectForKey:@"voice"] copy];
            
            NSString * voiceId =[voiceDic objectForKey:@"id"] ;
            
            
            self.voiceId = voiceId;
            
            NSString * time =[voiceDic objectForKey:@"time"];
            
            debugLog(@"time=%@",time);
            
            self.voiceDuration =time;
            
            
            NSString * voiceUrl =[fileUrlServer stringByAppendingFormat:@"/%@",self.voiceId];
            
            debugLog(@"voiceUrl=%@",voiceUrl);
            
            if(msgTypeInterger == YNBubbleMessageChatTypeWeChatVoice)
            {
                self.chatType = YNBubbleMessageChatTypeWeChatVoice;
            }
            else if (msgTypeInterger == YNBubbleMessageChatTypeGroupChatVoice)
            {
                self.chatType = YNBubbleMessageChatTypeGroupChatVoice;
                if ([self.friendId rangeOfString:ProjectTeamFlag].length > 0) {
                    self.chatType = YNBubbleMessageChatTypeProjectTeamVoice;
                }
            }
            else
            {
                self.chatType = YNBubbleMessageChatTypeDiscussionVoice;
                
            }
            self.voicePath = voicePath;

        }
        
        else
        {
            
            if ([self.friendId rangeOfString:DiscussionGroupFlag].length > 0)
            {
                self.chatType = YNBubbleMessageChatTypeDiscussion;
                
            }
            else if ([self.friendId rangeOfString:UserGroupFlag].length > 0)
            {
                self.chatType = YNBubbleMessageChatTypeGroupChat;
            }
            else
            {
                self.chatType = YNBubbleMessageChatTypeProjectTeamChat;
            }

        }
        
        //消息类型
        self.messageMediaType = manyPeopleChat.messageType;
        self.message = manyPeopleChat.messageBody;
    }
    return self;
}

/**
 *  根据单人会话数据表创建消息对象
 */
- (instancetype)initMessageWithTwoPeopleChatTabel:(YNTwoPeopleChat *)twoPeopleChat fileUploadUrlServer:(NSString*)fileUrlServer voicePath:(NSString*)voicePath
{
    self = [super init];
    if (self)
    {
        self.text = twoPeopleChat.message;
        self.body = twoPeopleChat.content;
        self.bubbleMessageType = twoPeopleChat.masterType;
        self.sendTime = twoPeopleChat.mTime;
        self.currentTime = self.sendTime;
        self.sendState = twoPeopleChat.isSuccess;
        self.isRead = twoPeopleChat.isReaded;
        self.friendId = twoPeopleChat.chatUserNo;
        self.packetId = twoPeopleChat.packId;
        self.chatType = YNBubbleMessageChatTypeWeChat;
        self.fileName = twoPeopleChat.fileName;
        self.messageHeight = twoPeopleChat.messageHeight;
        self.isMessageWithdraw = twoPeopleChat.isMessageWithdraw;
        
        
        //2016-7-15jc添加
        NSString * messageBody =[twoPeopleChat.messageBody copy];
        
        NSDictionary *msgDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:messageBody];
        
        NSString * msgType =[[msgDic objectForKey:@"msgType"] copy];
        
        
        NSInteger msgTypeInterger = [msgType integerValue];
        
        if(msgTypeInterger == YNBubbleMessageChatTypeWeChatVoice ||msgTypeInterger == YNBubbleMessageChatTypeGroupChatVoice || msgTypeInterger == YNBubbleMessageChatTypeDiscussionVoice)
        {
            NSMutableDictionary * voiceDic =[[msgDic objectForKey:@"voice"] copy];
            
            NSString * voiceId =[voiceDic objectForKey:@"id"] ;
            debugLog(@"voiceID=%@",voiceId);
            
            self.voiceId = voiceId;
            
            NSString * time =[voiceDic objectForKey:@"time"];
            
            debugLog(@"time=%@",time);
            
            self.voiceDuration =time;
            

            
            
            NSString * voiceUrl =[fileUrlServer stringByAppendingFormat:@"/%@",self.voiceId];
            
            debugLog(@"voiceUrl=%@",voiceUrl);
            
            if(msgTypeInterger == YNBubbleMessageChatTypeWeChatVoice)
            {
                 self.chatType = YNBubbleMessageChatTypeWeChatVoice;
            }
            else if (msgTypeInterger == YNBubbleMessageChatTypeGroupChatVoice)
            {
                self.chatType = YNBubbleMessageChatTypeGroupChatVoice;
                if ([self.friendId rangeOfString:ProjectTeamFlag].length > 0) {
                    self.chatType = YNBubbleMessageChatTypeProjectTeamVoice;
                }
            }
            else if(msgTypeInterger == YNBubbleMessageChatTypeFileWeChat)
            {
                self.chatType = YNBubbleMessageChatTypeFileWeChat;
            }
            else
            {
                self.chatType = YNBubbleMessageChatTypeDiscussionVoice;

            }
            
        }
        
        
        if([twoPeopleChat.message isEqualToString:@"voice"])
        {
            //            NSMutableDictionary * voice = twoPeopleChat.messageBody
        }
        self.voicePath = voicePath;
        if (self.bubbleMessageType)
        {
            self.fromUserId = twoPeopleChat.chatUserNo;
            self.toUserId = [YNIMmanager sharedInstance].userImId;
        }
        else
        {
            self.toUserId = twoPeopleChat.chatUserNo;
            self.fromUserId = [YNIMmanager sharedInstance].userImId;
        }
        
        self.messageMediaType = twoPeopleChat.messageType;
        self.message = twoPeopleChat.messageBody;
    }
    return self;
}



#pragma mark - sendMessage needs meesage model
/**
 初始化回执消息
 
 @param toUserId 对方id、群讨论组id
 @return 消息对象
 */
- (instancetype)initWithReceiptMessageToUserId:(NSString *)toUserId{
    if (self=[super init]) {
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.packetId = [XMPPStream generateUUID];
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
    }
    return self;
}

/**
 *  视频会议消息 文本消息(纯文本消息)
 *
 *  @param text         发送的目标文本
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initMeetingMessageWithText:(NSString *)text
                                 mettingId:(NSString *)mettingId{
    self = [super init];
    if (self)
    {
        self.text = text;
        self.body = text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.friendId = self.toUserId;
        self.packetId = [XMPPStream generateUUID];
        self.chatType = YNBubbleMessageChatTypeGroupChat;
        self.mettingId=mettingId;
        self.messageMediaType = YNBubbleMessageText;
        self.message = [self creatMeetingTextBodyBy:text mettingId:mettingId];
    }
    return self;
}

/**
 *  发送消息创建的Body
 *  message 消息
 *  pic     有图片需要加
 *  file    有文件需要加
 */
- (NSString *)creatMeetingTextBodyBy:(NSString *)message mettingId:(NSString *)mettingId
{
    //设置消息内容
    NSMutableDictionary *messageDic = [NSMutableDictionary dictionary];
    [messageDic setObject:message forKey:@"content"];
    [messageDic setObject:@101 forKey:@"msgType"];
    [messageDic setObject:@"meeting" forKey:@"resource"];
    [messageDic setObject:@[] forKey:@"images"];
    //设置自定义表情
    [messageDic setObject:@[] forKey:@"customAvatars"];
    [messageDic setObject:@[] forKey:@"files"];
    
    //设置字体风格
    NSMutableDictionary *fontDictionary = [NSMutableDictionary dictionary];
    
    //默认字体显示风格
    [fontDictionary setObject:@"宋体" forKey:@"fontFamily"];
    [fontDictionary setObject:@"#FF000000" forKey:@"foreground"];
    [fontDictionary setObject:[NSNumber numberWithInt:12] forKey:@"fontSize"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isUnderline"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isItalic"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isBold"];
    [messageDic setObject:fontDictionary forKey:@"style"];
    
    //2018-6-7jc添加，直播会议聊天时，需要添加会议ID
    if(![YNIMTool isEmptyString:mettingId])
    {
        NSMutableDictionary *videoDaction = [NSMutableDictionary dictionary];
        [videoDaction setObject:mettingId forKey:@"mettingId"];
        [messageDic setObject:videoDaction forKey:@"video"];
    }
    
    //设置名字
    [messageDic setObject:[YNIMmanager sharedInstance].userName forKey:@"sendName"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageDic options:NSJSONWritingPrettyPrinted  error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

/**
 *  初始化混合图片，文本消息(纯文本消息)
 *
 *  @param text         发送的目标文本
 *  @param toUserId     接收者的UserId
 *  @param chatType     消息类型
 *  @param groupName    群名字(如果是群消息)
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initWithMixText:(NSString *)text
                       toUserId:(NSString *)toUserId
                       chatType:(YNBubbleMessageChatType)chatType
                      groupName:(NSString *)groupName
                      mettingId:(NSString *)mettingId
                           body:(NSString *)body
                        message:(NSString *)message;
{
    self = [super init];
    if (self)
    {
        self.text = text;
        self.body = body;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.packetId = [XMPPStream generateUUID];
        self.chatType = chatType;
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChat:
            case YNBubbleMessageChatTypeDiscussion:
            case YNBubbleMessageChatTypeProjectTeamChat:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
                break;
            case YNBubbleMessageChatTypeNotification:
                break;
            case YNBubbleMessageChatTypeWeChat:
                break;
            default:
                break;
        }
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        self.messageMediaType = YNBubbleMessageMix;
        self.message = [self creatMixTextBodyByMessage:body message:message mettingId:mettingId];
    }
    return self;
}


/**
 *  初始化文本消息(纯文本消息)
 *
 *  @param text         发送的目标文本
 *  @param toUserId     接收者的UserId
 *  @param chatType     消息类型
 *  @param groupName    群名字(如果是群消息)
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initWithText:(NSString *)text
                    toUserId:(NSString *)toUserId
                    chatType:(YNBubbleMessageChatType)chatType
                   groupName:(NSString *)groupName
                   mettingId:(NSString *)mettingId;
{
    self = [super init];
    if (self)
    {
        self.text = text;
        self.body = text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.packetId = [XMPPStream generateUUID];
        self.chatType = chatType;
        self.mettingId=mettingId;
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChat:
            case YNBubbleMessageChatTypeDiscussion:
            case YNBubbleMessageChatTypeProjectTeamChat:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
                break;
            case YNBubbleMessageChatTypeNotification:
                break;
            case YNBubbleMessageChatTypeWeChat:
                break;
            default:
                break;
        }
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        self.messageMediaType = YNBubbleMessageText;
        self.message = [self creatTextBodyByMessage:text imageModel:nil fileDic:nil mettingId:mettingId];
    }
    return self;
}

/**
 *  初始化图片类型的消息
 */
- (instancetype)initWithAssets:(PictureModel*)assets
                      toUserId:(NSString *)toUserId
                      chatType:(YNBubbleMessageChatType)chatType
                     groupName:(NSString *)groupName
{
    if (self = [super init])
    {
        self.photo = assets.thumbnail;
        self.fileName = assets.imageName;
        self.originPhotoUrl = assets.originalPath;
        self.originPhoto = assets.originalImage;
        //2017-2-24jc添加
        self.compressImage  = assets.compressImage;
        self.compressPath=assets.compressPath;
        self.isCompressImage = assets.isCompressImage;
        //消息id
        self.packetId =[XMPPStream generateUUID];
        self.text = [NSString stringWithFormat:@"<img key=\"%@\">", assets.key];
        self.body = self.text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.chatType= chatType;
        
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChat:
            case YNBubbleMessageChatTypeDiscussion:
            case YNBubbleMessageChatTypeProjectTeamChat:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
                break;
            case YNBubbleMessageChatTypeNotification:
                break;
            case YNBubbleMessageChatTypeWeChat:
                break;
            default:
                break;
        }
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        self.messageMediaType = YNBubbleMessagePhoto;
        self.message = [self creatTextBodyByMessage:self.text imageModel:assets fileDic:nil mettingId:nil];
        
    }
    return self;
}

/**
 *  直播会议期间初始化图片类型的消息
 */
- (instancetype)initMeetingImageMessageWithAssets:(PictureModel *)assets
                                        mettingId:(NSString *)mettingId downUrl:(NSString*)downUrl
{
    if (self = [super init])
    {
        self.photo = assets.thumbnail;
        self.fileName = assets.imageName;
        self.originPhotoUrl = assets.originalPath;
        self.originPhoto = assets.originalImage;
        self.compressImage  = assets.compressImage;
        self.compressPath=assets.compressPath;
        self.isCompressImage = assets.isCompressImage;
        self.mettingId=mettingId;
        
        self.text = [NSString stringWithFormat:@"<img key=\"%@\">", assets.key];
        self.body = self.text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeReceiving;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.friendId = self.toUserId;
        self.chatType= YNBubbleMessageChatTypeGroupChat;
        self.messageMediaType = YNBubbleMessagePhoto;
        self.message = [self creatMeetingImageBodyByMessage:self.text imageModel:assets downUrl:downUrl];
        self.messageHeight = assets.thumbnail.size.height;
    }
    return self;
}

/**
 *  直播间发送图片创建的Body
 */
- (NSString *)creatMeetingImageBodyByMessage:(NSString *)message imageModel:(PictureModel *)pic downUrl:(NSString*)downUrlStr
{
    //设置消息内容
    NSMutableDictionary *messageDic = [NSMutableDictionary dictionary];
    [messageDic setObject:message forKey:@"content"];
    [messageDic setObject:@101 forKey:@"msgType"];
    /**HX** 设置消息来源于手机资源 **/
    [messageDic setObject:kResource_Msg_Phone forKey:@"resource"];
    //判断是否有图片
    if (pic)
    {
        NSMutableDictionary *image = [NSMutableDictionary dictionary];
        if ([YNIMTool isEmptyString:pic.key]) {
            pic.key=@"";
        }
        if ([YNIMTool isEmptyString:pic.imageName]) {
            pic.imageName=@"";
        }
        [image setObject:pic.key forKey:@"key"];
        [image setObject:pic.imageName forKey:@"name"];
        [image setObject:[NSString stringWithFormat:@"%lld", pic.imageSize] forKey:@"size"];
        [image setObject:@"1" forKey:@"fileType"];  //0:普通文件,1:图片,2:音频,3:视频,4:office文档
        [image setObject:pic.key forKey:@"fileId"];
        
        CGFloat width =pic.originalImage.size.width==0 ? 100 : pic.originalImage.size.width;
        CGFloat height = pic.originalImage.size.height==0 ? 100 : pic.originalImage.size.height;
        
        [image setObject:[NSString stringWithFormat:@"%f", width] forKey:@"width"];
        [image setObject:[NSString stringWithFormat:@"%f", height] forKey:@"height"];
        [image setObject:pic.key forKey:@"samllImageId"];
        if ([YNIMTool isEmptyString:pic.originalPath]) {
            pic.originalPath=@"";
        }
        [image setObject:pic.originalPath forKey:@"imageLocation"];
        [image setObject:downUrlStr forKey:@"downloadUrl"];
        
        NSArray *images = [NSArray arrayWithObject:image];
        [messageDic setObject:images forKey:@"images"];
    }
    else
    {
        [messageDic setObject:@[] forKey:@"images"];
    }
    [messageDic setObject:@[] forKey:@"files"];
    
    [messageDic setObject:[YNIMmanager sharedInstance].userName forKey:@"sendName"];
    [messageDic setObject:[YNIMmanager sharedInstance].userImId forKey:@"sendNo"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageDic options:NSJSONWritingPrettyPrinted  error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

//初始化文件消息对象
- (instancetype)initWithFileName:(NSString *)fileName
                        filePath:(NSString*)originPath
                          fileId:(NSString*)fileId
                 transpondFileId:(NSString*)transpondFileId
                        fileSize:(NSUInteger)fileSize
                        toUserId:(NSString *)toUserId
                        chatType:(YNBubbleMessageChatType)chatType
                       groupName:(NSString *)groupName
{
    if (self)
    {
        self.fileName = fileName;
        self.originPhotoUrl =originPath;
        self.packetId = [XMPPStream generateUUID];
        if ([YNIMTool isEmptyString:transpondFileId]) {
            fileId=self.packetId;
        }
        self.text = [NSString stringWithFormat:@"<file key=\"%@\">", fileId];
        
        self.body = self.text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.chatType = chatType;
        
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChat:
            case YNBubbleMessageChatTypeDiscussion:
            case YNBubbleMessageChatTypeProjectTeamChat:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
                break;
            case YNBubbleMessageChatTypeNotification:
                break;
            case YNBubbleMessageChatTypeWeChat:
                break;
            default:
                break;
        }
        
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        self.messageMediaType = YNBubbleMessageFile;
        self.fileState = fileStateUploading;
        if ([YNIMTool isEmptyString:fileName]) {
            fileName = @"";
        }
        if ([YNIMTool isEmptyString:fileId]) {
            fileId = @"";
        }
        self.message = [self creatTextBodyByMessage:self.text imageModel:nil fileDic:@{@"fileName":fileName,@"fileSize":@(fileSize),@"fileId":fileId,@"sourceUrl":fileName} mettingId:nil];
    }
    return self;
}


/**
 *  初始化语音类型的消息
 *
 *  @param voicePath        目标语音的本地路径
 *  @param voiceUrl         目标语音在服务器的地址
 *  @param voiceDuration    目标语音的时长
 *  @param sender           发送者
 *  @param date             发送时间
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initWithVoiceId:(NSString *)voiceId
                           time:(NSString *)time
                         sender:(NSString *)sender
                       toUserId:(NSString *)toUserId
                      groupName:(NSString *)groupName
                      voicePath:(NSString *)voicePath
                       chatType:(YNBubbleMessageChatType)chatType

{
    
    
    return [self initWithVoiceId:voiceId time:time sender:sender toUserId:toUserId groupName:groupName voicePath:voicePath chatType:chatType isRead:YES];
    
}

/**
 初始化文本消息(文件接收的文本消息)
 
 @param text 发送的目标文本
 @param packetId 文本的packetId
 @param toUserId 接收者的UserId
 @param chatType 消息类型
 @param groupName 群名字(如果是群消息)
 @return 返回Message model 对象
 */
- (instancetype)initWithReturnFileText:(NSString *)text
                              packetId:(NSString *)packetId
                              toUserId:(NSString *)toUserId
                              chatType:(YNBubbleMessageChatType)chatType
                             groupName:(NSString *)groupName;
{
    self = [super init];
    if (self)
    {
        self.text = text;
        self.body = text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        //先设置packetId，后面来改
        self.packetId = packetId;
        self.chatType = chatType;
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChat:
            case YNBubbleMessageChatTypeDiscussion:
            case YNBubbleMessageChatTypeProjectTeamChat:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
                break;
            case YNBubbleMessageChatTypeNotification:
                break;
            case YNBubbleMessageChatTypeWeChat:
                break;
            default:
                break;
        }
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        self.messageMediaType = YNBubbleMessageText;
        self.message = [self creatTextBodyByMessage:text imageModel:nil fileDic:nil mettingId:nil];
        //改成guid
        self.packetId = [XMPPStream generateUUID];
    }
    return self;
}


/**
 *  初始化语音类型的消息。增加已读未读标记
 *
 *  @param voicePath        目标语音的本地路径
 *  @param voiceUrl         目标语音在服务器的地址
 *  @param voiceDuration    目标语音的时长
 *  @param sender           发送者
 *  @param date             发送时间
 *  @param isRead           已读未读标记
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initWithVoiceId:(NSString *)voiceId
                           time:(NSString *)time
                         sender:(NSString *)sender
                       toUserId:(NSString *)toUserId
                      groupName:(NSString *)groupName
                      voicePath:(NSString *)voicePath
                       chatType:(YNBubbleMessageChatType )chatType
                         isRead:(BOOL)isRead
{

    
    self = [super init];
    if (self)
    {
        self.packetId = [XMPPStream generateUUID];
        self.text = [NSString stringWithFormat:@"[语音]"];
        self.body = self.text;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.chatType = chatType;
        self.voiceId=voiceId;
        self.voiceDuration= time;
        self.sender=sender;
        self.voicePath=voicePath;
        
        //jc添加
        self.messageMediaType=YNBubbleMessageVoice;
        
        
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChatVoice:
            case YNBubbleMessageChatTypeDiscussionVoice:
            case YNBubbleMessageChatTypeProjectTeamVoice:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
                break;
            case YNBubbleMessageChatTypeNotification:
                break;
            case YNBubbleMessageChatTypeWeChat:
                break;
            case YNBubbleMessageChatTypeWeChatVoice:
                break;
            default:
                break;
        }
        self.friendName = [YNIMmanager sharedInstance].userName;
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        VoiceModel * voiceModel =[[VoiceModel alloc]init];
        voiceModel.voiceId = voiceId;
        voiceModel.time= time;
        
        
        self.message = [self creatVoiceBodyByMessage:self.text voiceModel:voiceModel];
    }
    return self;
    
}



/**
 *  初始化视频类型的消息
 *
 *  @param videoConverPhoto 目标视频的封面图
 *  @param videoPath        目标视频的本地路径，如果是下载过，或者是从本地发送的时候，会存在
 *  @param videoUrl         目标视频在服务器上的地址
 *  @param sender           发送者
 *  @param date             发送时间
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initWithVideoConverPhoto:(UIImage *)videoConverPhoto
                               videoPath:(NSString *)videoPath
                                videoUrl:(NSString *)videoUrl
                                  sender:(NSString *)sender {
    self = [super init];
    if (self) {
        self.videoConverPhoto = videoConverPhoto;
        self.videoPath = videoPath;
        self.videoUrl = videoUrl;
        
        self.sender = sender;
        
        self.messageMediaType = YNBubbleMessageVideo;
    }
    return self;
}

///**
// *  初始化语音类型的消息
// *
// *  @param voicePath        目标语音的本地路径
// *  @param voiceUrl         目标语音在服务器的地址
// *  @param voiceDuration    目标语音的时长
// *  @param sender           发送者
// *  @param date             发送时间
// *
// *  @return 返回Message model 对象
// */
//- (instancetype)initWithVoicePath:(NSString *)voicePath
//                         voiceUrl:(NSString *)voiceUrl
//                    voiceDuration:(NSString *)voiceDuration
//                           sender:(NSString *)sender {
//
//    return [self initWithVoicePath:voicePath voiceUrl:voiceUrl voiceDuration:voiceDuration sender:sender isRead:YES];
//}
//
///**
// *  初始化语音类型的消息。增加已读未读标记
// *
// *  @param voicePath        目标语音的本地路径
// *  @param voiceUrl         目标语音在服务器的地址
// *  @param voiceDuration    目标语音的时长
// *  @param sender           发送者
// *  @param date             发送时间
// *  @param isRead           已读未读标记
// *
// *  @return 返回Message model 对象
// */
//- (instancetype)initWithVoicePath:(NSString *)voicePath
//                         voiceUrl:(NSString *)voiceUrl
//                    voiceDuration:(NSString *)voiceDuration
//                           sender:(NSString *)sender
//                           isRead:(BOOL)isRead {
//    self = [super init];
//    if (self) {
//        self.voicePath = voicePath;
//        self.voiceUrl = voiceUrl;
//        self.voiceDuration = voiceDuration;
//
//        self.sender = sender;
//        self.isRead = isRead;
//
//        self.messageMediaType = YNBubbleMessageVoice;
//    }
//    return self;
//}




/**
 *  初始化一个单独的表情消息模型
 */
- (instancetype)initWithEmotionName:(NSString *)emotionName
                        emotionPath:(NSString *)emotionPath
                           toUserId:(NSString *)toUserId
                           chatType:(YNBubbleMessageChatType)chatType
                          groupName:(NSString *)groupName
{
    self = [super init];
    if (self)
    {
        self.text = emotionName;
        self.body = emotionName;
        self.sendTime = [self dateStringFromCurrentDate];
        self.currentTime = [self dateStringFromMINDate:self.sendTime];
        self.bubbleMessageType = YNBubbleMessageTypeSending;
        self.isRead = YES;
        self.sendState = YNMessageSendStateSending;
        self.toUserId = toUserId;
        self.friendId = self.toUserId;
        self.packetId = [XMPPStream generateUUID];
        self.sender = [YNIMmanager sharedInstance].userName;
        self.chatType = chatType;
        self.emotionPath = emotionPath;
        
        switch (self.chatType) {
            case YNBubbleMessageChatTypeGroupChat:
            case YNBubbleMessageChatTypeDiscussion:
            case YNBubbleMessageChatTypeProjectTeamChat:
            case YNBubbleMessageChatTypeGroupChatVoice:
            case YNBubbleMessageChatTypeDiscussionVoice:
            case YNBubbleMessageChatTypeProjectTeamVoice:
            {
                self.groupName = groupName;
            }
                break;
            case YNBubbleMessageChatTypeBroadcast:
            case YNBubbleMessageChatTypeNotification:
            case YNBubbleMessageChatTypeWeChat:
                break;
            default:
                break;
        }
        
        self.fromUserId = [YNIMmanager sharedInstance].userImId;
        
        self.messageMediaType = YNBubbleMessageFace;
    }
    return self;
}

- (instancetype)initWithLocalPositionPhoto:(UIImage *)localPositionPhoto
                              geolocations:(NSString *)geolocations
                                  location:(CLLocation *)location
                                    sender:(NSString *)sender{
    self = [super init];
    if (self) {
        self.localPositionPhoto = localPositionPhoto;
        self.geolocations = geolocations;
        self.location = location;
        
        self.sender = sender;
        
        self.messageMediaType = YNBubbleMessageLocalPosition;
    }
    return self;
}

/**
 *  发送消息的时候根据发送的消息的类型来初始化消息对象(初始化混合内型消息)
 *
 *  @param messageDic           初始化发送消息对象相关的信息
 *  @param messageMediaType     消息格式的类型
 *
 *  @return 返回Message model 对象
 */
- (instancetype)initWithMessageDictionary:(NSDictionary *)messageDic bubbleMessageMediaType:(YNBubbleMessageMediaType)messageMediaType
{
    self = [super init];
    if (self)
    {
        
    }
    return self;
}

- (void)dealloc {
    _text = nil;
    
    _photo = nil;
    _fileName = nil;
    _originPhotoUrl = nil;
    
    _videoConverPhoto = nil;
    _videoPath = nil;
    _videoUrl = nil;
    
    _voicePath = nil;
    _voiceDuration = nil;
    
    _emotionPath = nil;
    
    _localPositionPhoto = nil;
    _geolocations = nil;
    _location = nil;
    
    _avatar = nil;
    _avatarUrl = nil;
    
    _sender = nil;
    _fromUserId = nil;
    _toUserId = nil;
    _body = nil;
    _sendTime = nil;
    _subject = nil;
    _currentTime = nil;
    _friendId = nil;
    _friendName = nil;
    _packetId = nil;
    _message = nil;
    _groupName = nil;
    
    
}
#pragma mark -  privideMethod
//html转义
+ (NSString *)covertJsonWithHTML:(NSString *)body
{
    if ([body rangeOfString:@"&"].length == 0)
    {
        return body;
    }
    NSRegularExpression *amp = [NSRegularExpression regularExpressionWithPattern:@"&amp;"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];
    NSRegularExpression *lt = [NSRegularExpression regularExpressionWithPattern:@"&lt;"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];
    NSRegularExpression *gt = [NSRegularExpression regularExpressionWithPattern:@"&gt;"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];
    NSRegularExpression *nbsp = [NSRegularExpression regularExpressionWithPattern:@"&nbsp;"
                                                                          options:NSRegularExpressionCaseInsensitive
                                                                            error:nil];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&#39;"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
    NSRegularExpression *quot = [NSRegularExpression regularExpressionWithPattern:@"&quot;"
                                                                          options:NSRegularExpressionCaseInsensitive
                                                                            error:nil];
    
    NSString *str1 = [amp stringByReplacingMatchesInString:body
                                                   options:NSMatchingReportProgress
                                                     range:NSMakeRange(0, body.length)
                                              withTemplate:@"&"];
    NSString *str2 = [lt stringByReplacingMatchesInString:str1
                                                  options:NSMatchingReportProgress
                                                    range:NSMakeRange(0, str1.length)
                                             withTemplate:@"<"];
    NSString *str3 = [gt stringByReplacingMatchesInString:str2
                                                  options:NSMatchingReportProgress
                                                    range:NSMakeRange(0, str2.length)
                                             withTemplate:@">"];
    NSString *str4 = [nbsp stringByReplacingMatchesInString:str3
                                                    options:NSMatchingReportProgress
                                                      range:NSMakeRange(0, str3.length)
                                               withTemplate:@" "];
    NSString *str5 = [regex stringByReplacingMatchesInString:str4
                                                     options:NSMatchingReportProgress
                                                       range:NSMakeRange(0, str4.length)
                                                withTemplate:@"\'"];
    NSString *str6 = [quot stringByReplacingMatchesInString:str5
                                                    options:NSMatchingReportProgress
                                                      range:NSMakeRange(0, str5.length)
                                               withTemplate:@"\""];
    
    return str6;
}

//获取当前时间
- (NSString *)dateStringFromCurrentDate
{
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
    [dataFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *currentDataStr = [dataFormatter stringFromDate:[NSDate date]];
    return currentDataStr;
}

//获取发送时间
- (NSString *)dateStringFromMINDate:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (time)
    {
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
        NSDate *date = [dateFormatter dateFromString:time];
        if (date == nil)
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            date = [dateFormatter dateFromString:time];
        }
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *serverTime = [dateFormatter stringFromDate:date];
        return serverTime;
    }
    else
    {
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *localityTime = [dateFormatter stringFromDate:[NSDate date]];
        return localityTime;
    }
}

/**
 *  发送消息创建的Body
 *  message 消息
 *  pic     有图片需要加
 *  file    有文件需要加
 */
- (NSString *)creatTextBodyByMessage:(NSString *)message imageModel:(PictureModel *)pic fileDic:(NSDictionary *)fileDic mettingId:(NSString *)mettingId
{
    //设置消息内容
    NSMutableDictionary *messageDic = [NSMutableDictionary dictionary];
    [messageDic setObject:message forKey:@"content"];
    
    //设置消息类型
    NSString *numberStr = [NSString stringWithFormat:@"%d",(int)self.chatType];
    /**HX** 如果是项目组类型，则要将其转换为群对应的类型 **/
    if (self.chatType==YNBubbleMessageChatTypeProjectTeamChat) {
        numberStr = [NSString stringWithFormat:@"%d",(int)YNBubbleMessageChatTypeGroupChat];
    }
    if (self.chatType == YNBubbleMessageChatTypeProjectTeamVoice) {
        numberStr = [NSString stringWithFormat:@"%d",(int)YNBubbleMessageChatTypeGroupChatVoice];
    }

    [messageDic setObject:numberStr forKey:@"msgType"];
    
    /**HX** 设置消息来源于手机资源 **/
    [messageDic setObject:kResource_Msg_Phone forKey:@"resource"];
    //判断是否有图片
    if (pic)
    {
        NSMutableDictionary *image = [NSMutableDictionary dictionary];
        if ([YNIMTool isEmptyString:pic.key]) {
            pic.key=@"";
        }
        if ([YNIMTool isEmptyString:pic.imageName]) {
            pic.imageName=@"";
        }
        [image setObject:pic.key forKey:@"key"];
        [image setObject:pic.imageName forKey:@"name"];
        [image setObject:[NSString stringWithFormat:@"%lld", pic.imageSize] forKey:@"size"];
        [image setObject:@"1" forKey:@"fileType"];  //0:普通文件,1:图片,2:音频,3:视频,4:office文档
        [image setObject:pic.key forKey:@"fileId"];
        
        CGFloat width =pic.originalImage.size.width==0 ? 100 : pic.originalImage.size.width;
        CGFloat height = pic.originalImage.size.height==0 ? 100 : pic.originalImage.size.height;

        [image setObject:[NSString stringWithFormat:@"%f", width] forKey:@"width"];
        [image setObject:[NSString stringWithFormat:@"%f", height] forKey:@"height"];
        [image setObject:pic.key forKey:@"samllImageId"];
        if ([YNIMTool isEmptyString:pic.originalPath]) {
            pic.originalPath=@"";
        }
        [image setObject:pic.originalPath forKey:@"imageLocation"];
        
        NSArray *images = [NSArray arrayWithObject:image];
        [messageDic setObject:images forKey:@"images"];
    }
    else
    {
        [messageDic setObject:@[] forKey:@"images"];
    }
    
    //设置自定义表情
    [messageDic setObject:@[] forKey:@"customAvatars"];
    
    @try {
        //设置文件
        if (fileDic)
        {
            NSMutableDictionary *fileDicObj = [NSMutableDictionary dictionary];
            [fileDicObj setObject:self.packetId forKey:@"key"];
            [fileDicObj setObject:fileDic[@"fileName"] forKey:@"name"];
            [fileDicObj setObject:[NSString stringWithFormat:@"%ld", [fileDic[@"fileSize"]integerValue]] forKey:@"size"];
            [fileDicObj setObject:@"0" forKey:@"fileType"];
            [fileDicObj setObject:fileDic[@"fileId"] forKey:@"fileId"];
            [fileDicObj setObject:@"100" forKey:@"status"];
            [fileDicObj setObject:fileDic[@"sourceUrl"] forKey:@"sourcePath"];
            
            NSArray *files = [NSArray arrayWithObject:fileDicObj];
            [messageDic setObject:files forKey:@"files"];
        }
        else
        {
            [messageDic setObject:@[] forKey:@"files"];
        }
        
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
    //设置字体风格
    
    NSMutableDictionary *fontDictionary = [NSMutableDictionary dictionary];
    
    //默认字体显示风格
    [fontDictionary setObject:@"宋体" forKey:@"fontFamily"];
    [fontDictionary setObject:@"#FF000000" forKey:@"foreground"];
    [fontDictionary setObject:[NSNumber numberWithInt:12] forKey:@"fontSize"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isUnderline"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isItalic"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isBold"];
    [messageDic setObject:fontDictionary forKey:@"style"];
    //2018-6-7jc添加，直播会议聊天时，需要添加会议ID
    if(![YNIMTool isEmptyString:mettingId])
    {
        NSMutableDictionary *videoDaction = [NSMutableDictionary dictionary];
        [videoDaction setObject:mettingId forKey:@"mettingId"];
        [messageDic setObject:videoDaction forKey:@"video"];
    }

    //设置名字
    if (self.friendName != nil)
    {
        [messageDic setObject:self.friendName forKey:@"sendName"];
        self.sender = self.friendName;
    }
    else
    {
        [messageDic setObject:@"未知" forKey:@"sendName"];
    }
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageDic options:NSJSONWritingPrettyPrinted  error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}
#pragma end

/**
 *  发送消息创建的Body
 *  message 消息
 *  file    有文件需要加
 */
- (NSString *)creatMixTextBodyByMessage:(NSString *)text message:(NSString *)message mettingId:(NSString *)mettingId
{
    //设置消息内容
    NSMutableDictionary *messageDic = [NSMutableDictionary dictionary];
    [messageDic setObject:text forKey:@"content"];
    
    //设置消息类型
    NSString *numberStr = [NSString stringWithFormat:@"%d",(int)self.chatType];
    
    [messageDic setObject:numberStr forKey:@"msgType"];
    /**HX** 设置消息来源于手机资源 **/
    [messageDic setObject:kResource_Msg_Phone forKey:@"resource"];
    //判断是否有图片
    if (![YNIMTool isEmptyString:message])
    {
        NSDictionary * dict = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:message];
        NSMutableDictionary * mutableDict = [[NSMutableDictionary alloc]initWithDictionary:dict];
        NSArray * images = [mutableDict objectForKey:@"images"];
        
        NSMutableArray * imageArray = [NSMutableArray  array];
        
        for (int i = 0; i <images.count; i++) {
            NSDictionary * dict = images[i];
            
            NSMutableDictionary *image = [NSMutableDictionary dictionary];
            
            NSString * key =  @"";
            NSString * name =  [dict objectForKey:@"name"];
            NSString * size =  [dict objectForKey:@"size"];
            NSString * fileId =  [dict objectForKey:@"fileId"];
            NSString * imageLocation =  @"";
            
            [image setObject:key forKey:@"key"];
            [image setObject:name forKey:@"name"];
            [image setObject:size forKey:@"size"];
            [image setObject:@"1" forKey:@"fileType"];  //0:普通文件,1:图片,2:音频,3:视频,4:office文档
            [image setObject:fileId forKey:@"fileId"];
            
            [image setObject:@"" forKey:@"width"];
            [image setObject:@"" forKey:@"height"];
            [image setObject:key forKey:@"samllImageId"];
            
            [image setObject:imageLocation forKey:@"imageLocation"];
            
            [imageArray addObject:image];
            
        }
        [messageDic setObject:imageArray forKey:@"images"];
        
    }
    
    else
    {
        [messageDic setObject:@[] forKey:@"images"];
    }
    
    //设置自定义表情
    [messageDic setObject:@[] forKey:@"customAvatars"];
    
    [messageDic setObject:@[] forKey:@"files"];
    
    //设置字体风格
    
    NSMutableDictionary *fontDictionary = [NSMutableDictionary dictionary];
    
    //默认字体显示风格
    [fontDictionary setObject:@"宋体" forKey:@"fontFamily"];
    [fontDictionary setObject:@"#FF000000" forKey:@"foreground"];
    [fontDictionary setObject:[NSNumber numberWithInt:12] forKey:@"fontSize"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isUnderline"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isItalic"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isBold"];
    [messageDic setObject:fontDictionary forKey:@"style"];
    
    //2018-6-7jc添加，直播会议聊天时，需要添加会议ID
    if(![YNIMTool isEmptyString:mettingId])
    {
        NSMutableDictionary *videoDaction = [NSMutableDictionary dictionary];
        [videoDaction setObject:mettingId forKey:@"mettingId"];
        [messageDic setObject:videoDaction forKey:@"video"];
    }
    
    //设置名字
    if (self.friendName != nil)
    {
        [messageDic setObject:self.friendName forKey:@"sendName"];
        self.sender = self.friendName;
    }
    else
    {
        [messageDic setObject:@"未知" forKey:@"sendName"];
    }
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageDic options:NSJSONWritingPrettyPrinted  error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonString;
}

/**
 *  发送语音创建的Body
 *  message 消息
 *  pic     有图片需要加
 *  file    有文件需要加
 */
- (NSString *)creatVoiceBodyByMessage:(NSString *)message voiceModel:(VoiceModel *)voice
{
    //设置消息内容
    NSMutableDictionary *messageDic = [NSMutableDictionary dictionary];
    [messageDic setObject:message forKey:@"content"];
    
    //设置消息类型
    NSString *numberStr = [NSString stringWithFormat:@"%d",(int)self.chatType];
    /**HX** 如果是项目组类型，则要将其转换为群对应的类型 **/
    if (self.chatType==YNBubbleMessageChatTypeProjectTeamChat) {
        numberStr = [NSString stringWithFormat:@"%d",(int)YNBubbleMessageChatTypeGroupChat];
    }
    if (self.chatType == YNBubbleMessageChatTypeProjectTeamVoice) {
        numberStr = [NSString stringWithFormat:@"%d",(int)YNBubbleMessageChatTypeGroupChatVoice];
    }
    [messageDic setObject:numberStr forKey:@"msgType"];
    
    /**HX** 设置消息来源手机这个终端资源 **/
    [messageDic setObject:kResource_Msg_Phone forKey:@"resource"];
    
    [messageDic setObject:@[] forKey:@"images"];
    
    [messageDic setObject:@[] forKey:@"files"];
    
    NSMutableDictionary *voiceDic = [NSMutableDictionary dictionary];
    [voiceDic setObject:voice.voiceId forKey:@"id"];
    [voiceDic setObject:voice.time forKey:@"time"];
    
    //设置自定义表情
    [messageDic setObject:@[] forKey:@"customAvatars"];
    
    [messageDic setObject:voiceDic forKey:@"voice"];
    
    //设置字体风格
    
    NSMutableDictionary *fontDictionary = [NSMutableDictionary dictionary];
    
    //默认字体显示风格
    [fontDictionary setObject:@"宋体" forKey:@"fontFamily"];
    [fontDictionary setObject:@"#FF000000" forKey:@"foreground"];
    [fontDictionary setObject:[NSNumber numberWithInt:12] forKey:@"fontSize"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isUnderline"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isItalic"];
    [fontDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isBold"];
    [messageDic setObject:fontDictionary forKey:@"style"];
    
    //设置名字
    if (self.friendName != nil)
    {
        [messageDic setObject:self.friendName forKey:@"sendName"];
        self.sender = self.friendName;
    }
    else
    {
        [messageDic setObject:@"未知" forKey:@"sendName"];
    }
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageDic options:NSJSONWritingPrettyPrinted  error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    //    NSString *hemlStr = [jsonString stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
    //    hemlStr = [jsonString stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
    //    hemlStr = [jsonString stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    //    hemlStr = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@"&nbsp;"];
    //    hemlStr = [jsonString stringByReplacingOccurrencesOfString:@"\'" withString:@"&#39;"];
    //    hemlStr = [jsonString stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"];
    //    NSLog(@"----->%@",hemlStr);
    return jsonString;
}
#pragma end
//从字符串中获取文字内容
+ (NSString *)extractContentFromString:(NSString *)string
{
    //2017-12-11,JC添加。解决字符串为空时奔溃问题。
    if([YNIMTool isEmptyString:string])
    {
        return @"";
    }
    
    NSString *pattern = @"<a href=\'([^\"]*?)\'.+>(.*?)</a>";
    
    
    NSError *error;
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    
    NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
    NSMutableString *resultStr = [NSMutableString stringWithCapacity:0];
    NSMutableDictionary *markDic = [NSMutableDictionary dictionary];
    NSUInteger lastIdx = 0;
    for (NSTextCheckingResult* match in matches)
    {
        
        NSRange range = match.range;
        
        if (range.location > lastIdx)
        {
            
            NSString  *temp = [string substringWithRange:NSMakeRange(lastIdx, range.location - lastIdx)];
            
            [resultStr appendString:temp];
            
        }
        
        NSString *link = [string substringWithRange:[match rangeAtIndex:1]];
        
        NSString *text = [string substringWithRange:[match rangeAtIndex:2]];
        
        NSString *atName = [NSString stringWithFormat:@"%@",text];
        
        [resultStr appendString:atName];
        
        [markDic setObject:link forKey:atName];
        
        lastIdx = range.location + range.length;
    }
    
    if (lastIdx < string.length)
    {
        
        NSString  *temp = [string substringFromIndex:lastIdx];
        
        [resultStr appendString:temp];
        
    }
    
    return resultStr;
    
}
@end
